//
//  JUChatRoomVC.m
//  findFriend
//
//  Created by ju on 14-9-11.
//  Copyright (c) 2014年 dono. All rights reserved.
//

#import "JUChatRoomVC.h"
#import "BMKMapView.h"
#import "ChatGroup.h"
#import "BMKLocationService.h"
#import "MapProxy.h"

@interface JUChatRoomVC ()<BMKMapViewDelegate,UITableViewDataSource,UITableViewDelegate,AVGroupDelegate,BMKLocationServiceDelegate,UIAlertViewDelegate,AVSessionDelegate,AVSignatureDelegate>
{
    BMKMapView *_mapView;
    UITableView *_chat;
    BMKLocationService *_locationService;
    BMKUserLocation *_userLoc;
    
    AVGroup *_group;
    
    NSMutableDictionary *_friendsLocation;
    
    CGFloat timeDuration;
    NSTimer *sendTimer;
    UIAlertView *_setDurationView;
    
    MapProxy *_mapProxy;
    
    AVSession *_session;
}

@end


@implementation JUChatRoomVC

- (id)init
{
    self = [super init];
    if (self) {
        [self setupSession];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 初始化变量
    [self setupVariable];
    
    // 初始化右边的设置按钮
    [self setupSettingBtn];
    
    // 初始化选择条
    [self setupSegment];
    
    // 初始化Group
//    [self setupGroup];
    
    // 初始化定位类
    [self setupLocation];
    
    [self setupBaiduMap];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [sendTimer invalidate];
}

#pragma mark 初始化右边设置按钮
- (void)setupSettingBtn
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(setSendLocationTimeDuration:)];
}

- (void)setSendLocationTimeDuration:(UIBarButtonItem *)item
{
    [[self alertView] show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        UITextField *textField = [alertView textFieldAtIndex:0];
        timeDuration = [textField.text floatValue];
        [self setupTimer];
    }
}


#pragma mark 初始化定位类
- (void)setupLocation
{
    _locationService = [[BMKLocationService alloc] init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    [self setupTimer];
}

//开始定位
- (void)startLocate
{
    [_locationService startUserLocationService];
}

/**
 *在将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser
{
    NSLog(@"马上要启动定位");
}

/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser
{
    NSLog(@"停止定位");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    _userLoc = userLocation;
    [_mapView updateLocationData:userLocation];
    [_mapView setCenterCoordinate:_userLoc.location.coordinate animated:YES];
    [_locationService stopUserLocationService];
    [self sendLocation];
}

#pragma mark 初始化group
- (void)setupGroup
{
    if (!_chatGroup.groupId||[_chatGroup.groupId isEqualToString:@""]) {
        _group = [_session getGroup:nil];
    }else{
        _group = [_session getGroup:_chatGroup.groupId];
    }
    _group.delegate = self;
    NSLog(@"isopen:%d",_session.isOpen);
    [_group join];
}

#pragma mark 初始化segment
- (void)setupSegment
{
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"聊天室",@"地图"]];
    segmentControl.selectedSegmentIndex = 0;
    [segmentControl addTarget:self action:@selector(segmentedControlPressed:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentControl;
}

- (void)segmentedControlPressed:(UISegmentedControl *)segmentControl
{
    // 1.聊天室
    // 2.地图
}

#pragma mark 初始化地图
- (void)setupBaiduMap
{
    _mapView = [[BMKMapView alloc] initWithFrame:self.view.bounds];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    _mapProxy.mapView = _mapView;
    _mapView.delegate = _mapProxy;
    _mapView.showsUserLocation = YES;
    self.view = _mapView;
}

#pragma mark 初始化聊天界面
- (void)setupChatList
{
    _chat = [[UITableView alloc] initWithFrame:self.view.bounds];
    _chat.delegate = self;
    _chat.dataSource = self;
}

#pragma mark tableview数据源和代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"roomCell"];
    return cell;
}

#pragma mark AVGroup 代理
- (void)session:(AVSession *)session group:(AVGroup *)group didReceiveGroupMessage:(NSString *)message fromPeerId:(NSString *)peerId
{
    NSError *error;
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if (!error) {
        // 显示到地图上
        [self addAnotationWithDictionary:json userId:peerId];
    }else{
        NSLog(@"%@",error);
    }
}

//接受到小组成员的事件
- (void)session:(AVSession *)session group:(AVGroup *)group didReceiveGroupEvent:(AVGroupEvent)event memberIds:(NSArray *)memberIds
{
    if (event == AVGroupEventSelfJoined) {
        NSLog(@"自己成功加入小组");
        _chatGroup.groupId = group.groupId;
        [_chatGroup save];
        AVObject *obj = [AVObject objectWithClassName:@"ChatGroup"];
        obj[@"groupName"] = _chatGroup.groupName;
        obj[@"groupId"] = _chatGroup.groupId;
        [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            NSLog(@"%d",succeeded);
        }];
        
    }else if(event == AVGroupEventMemberJoined){
        NSLog(@"欢迎 %@ 加入小组",memberIds);
    }
}

//成功发送消息
- (void)session:(AVSession *)session group:(AVGroup *)group messageSent:(NSString *)message success:(BOOL)success
{
    
}

#pragma mark 初始化session
- (void)setupSession
{
    _session = [[AVSession alloc] init];
    _session.sessionDelegate = self;
    _session.signatureDelegate = self;
    [_session open:[AVUser currentUser].username withPeerIds:nil];
}

#pragma mark - AVSessionDelegate
- (void)onSessionOpen:(AVSession *)session {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@", session.getSelfPeerId);
    [self setupGroup];
}

- (void)onSessionPaused:(AVSession *)session {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@", session.getSelfPeerId);
}

- (void)onSessionResumed:(AVSession *)session {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@", session.getSelfPeerId);
}

- (void)onSessionMessage:(AVSession *)session message:(NSString *)message peerId:(NSString *)peerId {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ message:%@ peerId:%@", session.getSelfPeerId, message, peerId);
}

- (void)onSessionMessageFailure:(AVSession *)session message:(NSString *)message toPeerIds:(NSArray *)peerIds {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ message:%@ peerIds:%@", session.getSelfPeerId, message, peerIds);
}

- (void)onSessionMessageSent:(AVSession *)session message:(NSString *)message toPeerIds:(NSArray *)peerIds{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ message:%@ peerIds:%@", session.getSelfPeerId, message, peerIds);
}

- (void)onSessionStatusOnline:(AVSession *)session peers:(NSArray *)peerIds {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ peerIds:%@", session.getSelfPeerId, peerIds);
}

- (void)onSessionStatusOffline:(AVSession *)session peers:(NSArray *)peerId {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ peerIds:%@", session.getSelfPeerId, peerId);
}

- (void)onSessionError:(AVSession *)session withException:(NSException *)exception {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"session:%@ exception:%@", session.getSelfPeerId, exception);
}


#pragma mark 发送坐标数据
- (void)sendLocation
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSNumber *lat = [NSNumber numberWithDouble:_userLoc.location.coordinate.latitude];
    NSNumber *lng = [NSNumber numberWithDouble:_userLoc.location.coordinate.longitude];
    [dic setObject:lat forKey:@"lat"];
    [dic setObject:lng forKey:@"lng"];
    NSError *error ;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    if (!error) {
        NSString *payload = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [_group sendMessage:payload isTransient:NO];
    }else{
        NSLog(@"%@",error);
    }
}

#pragma mark 显示朋友的坐标到地图上
- (void)addAnotationWithDictionary:(NSDictionary *)json userId:(NSString *)userId
{
//    NSLog(@"%@ 的坐标是 %@",userId,json);
    [_mapProxy updateLocation:json userId:userId];
}

#pragma mark 初始化变量
- (void)setupVariable
{
    _friendsLocation = [NSMutableDictionary dictionary];
    timeDuration = 10;
    
    _mapProxy = [[MapProxy alloc] init];
    
//    [_session open:[AVUser currentUser].username withPeerIds:nil];
}

#pragma mark 设置Timer
- (void)setupTimer
{
    [sendTimer invalidate];
    __weak JUChatRoomVC *weakSelf = self;
    sendTimer = [NSTimer scheduledTimerWithTimeInterval:timeDuration target:weakSelf selector:@selector(startLocate) userInfo:nil repeats:YES];
}

- (UIAlertView *)alertView
{
    if (!_setDurationView) {
        _setDurationView = [[UIAlertView alloc] init];
        _setDurationView.title = @"设置发送坐标频率";
        [_setDurationView addButtonWithTitle:@"取消"];
        [_setDurationView addButtonWithTitle:@"确定"];
        _setDurationView.alertViewStyle = UIAlertViewStylePlainTextInput;
        _setDurationView.delegate = self;
    }
    return _setDurationView;
}

//- (void)setSession:(AVSession *)session
//{
//    _session = session;
//}

- (void)dealloc
{
    [_locationService stopUserLocationService];
    _locationService.delegate = nil;
    [sendTimer invalidate];
}

@end
